//
//  InvestViewController.m
//  Kjs-iOS
//
//  Created by cfq on 16/5/31.
//  Copyright © 2016年 jmhz. All rights reserved.
//

#import "InvestViewController.h"
#import "TransverseSelectView.h"
#import "HomeItemCell.h"
#import "ItemDetailViewController.h"
#import "KJSRequest.h"
#import "ConditionViewController.h"
#import <MJRefresh.h>



@interface InvestViewController()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet TransverseSelectView *transverseView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableDictionary *dic;
@end

@implementation InvestViewController

-(void)viewDidLoad{
    
    self.navigationItem.title = @"投资列表";
    self.naviTopView = YES;
    //设置更多按钮
    UIButton* rightButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [rightButton setImage:[UIImage imageNamed:@"invest-search"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(goSearch) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBtn;

    self.transverseView.titleArray = @[@"最新上线",@"年化收益率",@"项目期限"];
    self.transverseView.selectAction = ^(NSInteger selectLocation){
        self.items = [NSMutableArray array];
        self.page = 1;
        self.rows = 5;
        NSLog(@"选择 %ld",(long)selectLocation);
        switch (selectLocation) {
            case 0:
                self.sordid = @"itemPushFlag";
                if ([self.sord isEqualToString:@"ASC"]) {
                    self.sord = @"DESC";
                }else if ([self.sord isEqualToString:@"DESC"]){
                    self.sord = @"ASC";
                }else{
                    self.sord = @"DESC";
                }
                break;
            case 1:
                self.sordid = @"gdAnnualizedBenefitRate";
                if ([self.sord isEqualToString:@"ASC"]) {
                    self.sord = @"DESC";
                }else if ([self.sord isEqualToString:@"DESC"]){
                    self.sord = @"ASC";
                }else{
                    self.sord = @"DESC";
                }
                break;
            case 2:
                self.sordid = @"interestDays";
                if ([self.sord isEqualToString:@"ASC"]) {
                    
                    self.sord = @"DESC";
                }else if ([self.sord isEqualToString:@"DESC"]){
                    self.sord = @"ASC";
                }else{
                    self.sord = @"DESC";
                }
                break;
                
            default:
                break;
        }
        [self getItemByCond];
    };
    
    [self configuration];
    [self getItemByCond];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    if ([self.rules count] != 0) {
//        NSLog(@"到这里了");
//        self.items = [NSMutableArray array];
//        [self.dic setObject:self.rules forKey:@"rules"];
//        [self getItemByCond];
//    }else {
//        [self configrateParam];
//        [self getItemByCond];
//    }
}

#pragma mark - support method

- (void)getItemByCond
{
    NSLog(@"filter------%@",[self dictionaryToJson:self.dic]);
    NSLog(@"sord=%@------sordid=%@",self.sord,self.sordid);

    self.filter = [self dictionaryToJson:self.dic];
    [KJSRequest GetItemByCondtionWithPage:self.page Rows:self.rows Sordid:self.sordid sord:self.sord Filter:self.filter ret:^(ItemByCondModel *model) {
        [self.items addObjectsFromArray:model.items];
        [(MJRefreshAutoNormalFooter *)self.tableView.mj_footer setTitle:([model.items count] < ROW_OF_EACH_PAGE)? @"没有更多数据了" :@"上拉加载更多数据" forState:MJRefreshStateIdle];
        [self endRefresh];

        [self.tableView reloadData];
    }];
}

-(void)goSearch{
    
    NSLog(@"goSearch");
    ConditionViewController *conditionVC = [[UIStoryboard storyboardWithName:@"Seconed" bundle:nil] instantiateViewControllerWithIdentifier:@"ConditionViewController"];
    conditionVC.addRules = ^(NSMutableArray *rules){
        self.rules = rules;
        self.items = [NSMutableArray array];
        [self.dic setObject:self.rules forKey:@"rules"];
        [self getItemByCond];
        NSLog(@"调用了这里的代码块%@",self.rules);
    };
    [self displayViewController:conditionVC];
}
- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    NSError *parseError = nil;
    if ([dic count]!=0){
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
        return @"";
    }
    
}
#pragma mark - configure

- (void)configuration {
    [self configrateParam];
    [self configurateTableView];
    
}

- (void)configurateTableView {
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeItemCell" bundle:nil] forCellReuseIdentifier:@"HomeItemCell"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [footer setTitle:@"上拉加载更多数据" forState:MJRefreshStateIdle];
    [footer setTitle:@"用力拉！~" forState:MJRefreshStatePulling];
    [footer setTitle:@"更新数据中~" forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多数据" forState:MJRefreshStateNoMoreData];
    
    self.tableView.mj_footer = footer;
}

- (void)configrateParam
{
    self.page = 1;
    self.rows = 5;
    self.sord = @"";
    self.sordid = @"";
    self.items = [[NSMutableArray alloc] init];
    self.rules = [[NSMutableArray alloc] init];
    self.dic = [NSMutableDictionary dictionary];
    self.filter = @"";
}

#pragma mark - refresh method
- (void)headerRefresh {
    NSLog(@"刷新");
    [self configrateParam];
    [self getItemByCond];
}

- (void)footerRefresh {
    NSLog(@"加载更多");
    self.page += 1;
    [self getItemByCond];
}

- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeItemCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"HomeItemCell"];
    NSLog(@"indexpath.row=%ld",indexPath.row);
    if([self.items count] > indexPath.row){
        cell.item = self.items[indexPath.row];

    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"选中%ld",(long)indexPath.row);
    ItemDetailViewController *itemDetailVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"ItemDetailViewController"];
    itemDetailVC.itemId = self.items[indexPath.row].itemId;
    if (self.items[indexPath.row].itemStatus == 9) {
        itemDetailVC.benefitStepStr = self.items[indexPath.row].gdBenefitReturnStep;
    }
    [self displayViewController:itemDetailVC];
}



@end
